package com.hyq.learn.security.cipher;

import com.google.common.base.Stopwatch;
import com.hyq.learn.security.warrper.ContentCachingRequest;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;

/**
 * @author : heyuqin
 * @since : 2024/03/05 17:34
 */
public class CipherFilter extends AbstractCipherFilter {

    private static final Logger log = LoggerFactory.getLogger(CipherFilter.class);

    private final HandlerExceptionResolver handlerExceptionResolver;

    public CipherFilter(KeyProvider key, CipherAlgorithm cipherAlgorithm, CipherDecision cipherDecision, String headerName, HandlerExceptionResolver handlerExceptionResolver ) {
        super(key, cipherAlgorithm, cipherDecision, headerName);
        this.handlerExceptionResolver = handlerExceptionResolver;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean b = cipherDecision.validate((HttpServletRequest) request);
        log.debug("uri [{}] cipher decision result {}", ((HttpServletRequest) request).getRequestURI(), b);
        if (!b) {
            chain.doFilter(request, response);
            return;
        }
        handleFilterInternal((HttpServletRequest) request, (HttpServletResponse) response, chain);
    }

    private void handleFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        ContentCachingRequest contentCachingRequest;
        if (request instanceof ContentCachingRequest){
            contentCachingRequest = (ContentCachingRequest) request;
        }else {
            contentCachingRequest = new ContentCachingRequest(request);
        }
        Stopwatch stopwatch = Stopwatch.createStarted();

        try {
            decryptRequest(contentCachingRequest);
        } catch (Exception ex) {
            handlerExceptionResolver.resolveException(request, response, null, ex);
            return;
        } finally {
            log.debug("uri {} decrypt request elapse time {}ms", request.getRequestURI(), stopwatch.elapsed().toMillis());
        }
        chain.doFilter(contentCachingRequest, response);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
